package com.anji.gateway.utils;

import com.alibaba.fastjson.JSONObject;
import com.anji.plus.gaea.bean.ResponseBean;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.CollectionUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Optional;

/**
 * 网关工具类
 * @author lr
 * @since 2021-03-03
 */
public abstract class GaeaWebFluxUtils {

    /**
     * 用户名
     */
    public final static String USER_NAME = qualify("username");


    /**
     * 是否要跳过过滤器
     */
    public final static String SKIP = qualify("skip");

    /**
     * 路径匹配
     */
    public final static AntPathMatcher antPathMatcher = new AntPathMatcher();

    private static String qualify(String attr) {
        return GaeaWebFluxUtils.class.getName() + "." + attr;
    }

    /**
     * 处理响应
     * @param exchange
     * @param code
     * @return
     */
    public static Mono<Void> getFilterResult(ServerWebExchange exchange, String code,String message){

        ResponseBean responseBean = ResponseBean.builder().code(code).message(message).build();
        ServerHttpResponse response = exchange.getResponse();
        response.getHeaders().add("Content-Type", MediaType.APPLICATION_JSON_VALUE);
        response.getHeaders().add("Accept", MediaType.APPLICATION_JSON_VALUE);

        String responseString = JSONObject.toJSONString(responseBean);
        DataBuffer wrap = exchange.getResponse().bufferFactory()
                .wrap(StringUtils.getBytes(responseString, StandardCharsets.UTF_8));
        //响应
        return response.writeWith(Mono.just(wrap));
    }

    /**
     * 判断字符串是否在集合里
     * @param list
     * @param path
     * @return
     */
    public static boolean matchPath(List<String> list, String path) {

        if (CollectionUtils.isEmpty(list)) {
            return false;
        }

        if (!list.contains(path)) {
            Optional<String> any = list.stream().filter(s -> antPathMatcher.match(s, path)).findAny();
            return any.isPresent();
        }

        return true;
    }
}
